package system_sms_service

import (
	"encoding/json"
	"time"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/util/pointer"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
)

func (cls *Sms) SendTimeTo(ctx context.Context, log *model.SystemSmsLog) errors.Error {
	if nil == log {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_MS.S_MS.STT_TO.123428 异常的传入参数")

		return errors.ErrorServerInternalError("ISS_MS.S_MS.STT_TO.143436", "异常的传入参数")
	}

	if model.SystemSmsLogSendTypeTime != *log.SendType {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_MS.S_MS.STT_TO.183452 短信日志发送类型异常，当前类型为 %d", *log.SendType)

		return errors.ErrorServerInternalError("ISS_MS.S_MS.STT_TO.203459", "短信日志发送类型不正确")
	}

	if model.SystemSmsLogStatusPending != *log.Status {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_MS.S_MS.STT_TO.243542 短信日志状态异常，当前状态为 %d", *log.Status)

		return errors.ErrorServerInternalError("ISS_MS.S_MS.STT_TO.263548", "短信日志状态不正确")
	}

	log.Status = pointer.New(model.SystemSmsLogStatusSending)

	if err := cls.smsLog.SaveSystemSmsLog(ctx, log); nil != err {
		return err.Relation(errors.ErrorServerInternalError("ISS_MS.S_MS.STT_TO.333615", "更新短信日志状态失败"))
	}

	p, err := cls.GetProvider(*log.TemplateCode)
	if nil != err {
		return err.Relation(errors.ErrorServerInternalError("ISS_MS.S_MS.STT_TO.383648", "获取短信提供商失败"))
	}

	var params map[string]string
	if "" != *log.TemplateParams {
		if rerr := json.Unmarshal([]byte(*log.TemplateParams), &params); nil != rerr {
			logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_MS.S_MS.STT_TO.473840 反序列化模板参数失败，错误信息为 %q", rerr.Error())

			return errors.ErrorServerInternalError("ISS_MS.S_MS.STT_TO.493846", "反序列化模板参数失败")
		}
	}

	if err := p.Send(ctx, *log.Telephone, *log.TemplateCode, params); nil != err {
		log.Status = pointer.New(model.SystemSmsLogStatusFailed)
		log.FailedReason = pointer.New(err.Error())

		if err := cls.smsLog.SaveSystemSmsLog(ctx, log); nil != err {
			logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISS_MS.S_MS.STT_TO.573923 更新短信日志状态失败，错误信息为 %q", err.Error())
		}

		return err.Relation(errors.ErrorServerInternalError("ISS_MS.S_MS.STT_TO.603935", "发送短信失败"))
	}

	log.Provider = pointer.New(p.GetName())
	log.Status = pointer.New(model.SystemSmsLogStatusSuccess)
	log.CompleteTime = pointer.New(time.Now().Unix())

	if err := cls.smsLog.SaveSystemSmsLog(ctx, log); nil != err {
		return err.Relation(errors.ErrorServerInternalError("ISS_MS.S_MS.STT_TO.694036", "更新短信日志状态失败"))
	}

	return nil
}
